package com.krain.ddbb.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.krain.corelibrary.util.BaseActivityManager;
import com.krain.corelibrary.util.SpUtil;
import com.krain.ddbb.base.APP;
import com.krain.ddbb.constant.SpKeys;
import com.krain.ddbb.entity.AppApi;
import com.krain.ddbb.util.BaseUtil;
import com.orhanobut.logger.Logger;

import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EService;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Class description
 * 定位的service
 *
 * @author yamin
 * @date 2016/1/26 下午 04:16
 */
@EService
public class LocationService extends Service {
    AMapLocationClientOption mLocationOption;
    @App
    APP app;
    @Bean
    BaseUtil baseUtil;
    long space = 1000;
    AMapLocationClient mLocationClient = null;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        initLoaction();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    /**
     * 初始化高德地图定位的方法
     */
    void initLoaction() {
        //声明定位回调监听器
        //声明mLocationOption对象

        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(space);
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
    }


    /**
     * 定位的回调
     */
    AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (!app.isLogin()) return;
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //定位成功回调信息，设置相关消息
                    amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                    double lat = amapLocation.getLatitude();//获取纬度
                    double lng = amapLocation.getLongitude();//获取经度
                    if (lat > 0 && lng > 0) {
                        if (space == 1000) {
                            space = 60000;
                            mLocationClient.stopLocation();
                            initLoaction();
                        }
                        SpUtil.putString(SpKeys.LAT, String.valueOf(lat));
                        SpUtil.putString(SpKeys.LNG, String.valueOf(lng));
                    } else
                        baseUtil.showSnackBar(BaseActivityManager.getInstance().getTopActivity(), "定位失败,请重启APP再尝试" +
                                "");

                    runOnBackground(lat, lng);
                } else {
                    baseUtil.showSnackBar(BaseActivityManager.getInstance().getTopActivity(), "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }

            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        mLocationClient.onDestroy();
    }

    @Background
    void runOnBackground(double lat, double lng) {
        AppApi.getsInstance(getApplicationContext()).upLoadLocation(app.getmUserinfo().getAccess_token(), lat, lng);
    }
}
